<template>
  <div class="member-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>会员列表</span>
          <el-button type="primary" @click="handleAdd">新增会员</el-button>
        </div>
      </template>
      <el-table :data="memberData" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="rolename" label="真实名" />
        <el-table-column prop="icard" label="身份证号" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="address" label="地址" />
        <el-table-column prop="gradeName" label="会员等级" />
        <el-table-column prop="educationName" label="学历等级" />
        <el-table-column prop="learnName" label="学习等级" />
        <el-table-column prop="gmtCreate" label="创建时间" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加会员对话框 -->
    <el-dialog
      title="新增会员"
      v-model="addDialogVisible"
      width="600px"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="rolename">
          <el-input v-model="addForm.rolename" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="icard">
          <el-input v-model="addForm.icard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="addForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAddForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑会员对话框 -->
    <el-dialog
      title="编辑会员"
      v-model="editDialogVisible"
      width="600px"
      @close="resetEditForm"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="editForm.password" type="password" placeholder="不修改请留空" show-password />
        </el-form-item>
        <el-form-item label="真实姓名" prop="rolename">
          <el-input v-model="editForm.rolename" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="icard">
          <el-input v-model="editForm.icard" placeholder="请输入身份证号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" placeholder="请输入地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm" :loading="submitLoading">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'


const route = useRoute()
const router = useRouter()
const loading = ref(false)
const submitLoading = ref(false)
const memberData = ref([])

// 添加表单相关
const addDialogVisible = ref(false)
const addFormRef = ref(null)
const addForm = reactive({
  username: '',
  password: '',
  rolename: '',
  icard: '',
  email: '',
  phone: '',
  address: ''
})

// 编辑表单相关
const editDialogVisible = ref(false)
const editFormRef = ref(null)
const editForm = reactive({
  id: '',
  username: '',
  password: '',
  rolename: '',
  icard: '',
  email: '',
  phone: '',
  address: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  rolename: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  icard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' }
  ]
}

// 编辑表单验证规则（密码可选）
const editRules = {
  ...rules,
  password: [
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 获取会员列表
const getMemberList = () => {
  loading.value = true
  axios({
    url: '/api/member/member/showAll',
    method: 'get'
  }).then((res) => {
    if (res.data.code === 200) {
      // 过滤出 logically_deleted 为 1 的数据
      memberData.value = res.data.data.filter(item => item.logicallyDeleted === 1)
    } else {
      ElMessage.error(res.data.msg || '获取会员列表失败')
    }
  }).catch((error) => {
    ElMessage.error('获取会员列表失败')
    console.error(error)
  }).finally(() => {
    loading.value = false
  })
}

// 重置添加表单
const resetAddForm = () => {
  if (addFormRef.value) {
    addFormRef.value.resetFields()
  }
  Object.assign(addForm, {
    username: '',
    password: '',
    rolename: '',
    icard: '',
    email: '',
    phone: '',
    address: ''
  })
}

// 重置编辑表单
const resetEditForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields()
  }
  Object.assign(editForm, {
    id: '',
    username: '',
    password: '',
    rolename: '',
    icard: '',
    email: '',
    phone: '',
    address: ''
  })
}

// 新增会员
const handleAdd = () => {
  addDialogVisible.value = true
}

// 编辑会员
const handleEdit = (row) => {
  Object.assign(editForm, {
    ...row,
    password: '' // 编辑时不显示密码
  })
  editDialogVisible.value = true
}

// 删除会员
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除会员"${row.username}"吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    axios({
      url: `/api/member/member/deleteMember/${row.id}`,
      method: 'put'
    }).then((res) => {
      if (res.data.code === 200) {
        ElMessage.success('删除成功')
        getMemberList()
      } else {
        ElMessage.error(res.data.msg || '删除失败')
      }
    }).catch((error) => {
      ElMessage.error('删除失败')
      console.error(error)
    })
  }).catch(() => {})
}

// 提交添加表单
const submitAddForm = () => {
  if (!addFormRef.value) return
  
  addFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      // 确保所有必填字段都有值
      if (!addForm.rolename) {
        ElMessage.error('请输入真实姓名')
        submitLoading.value = false
        return
      }

      const formData = new FormData()
      Object.keys(addForm).forEach(key => {
        formData.append(key, addForm[key])
      })

      axios({
        url: '/api/member/member/addMember',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('添加成功')
          addDialogVisible.value = false
          getMemberList()
        } else {
          ElMessage.error(res.data.msg || '添加失败')
        }
      }).catch((error) => {
        console.error('添加错误:', error)
        ElMessage.error('添加失败')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

// 提交编辑表单
const submitEditForm = () => {
  if (!editFormRef.value) return
  
  editFormRef.value.validate((valid) => {
    if (valid) {
      submitLoading.value = true
      const submitData = { ...editForm }
      // 如果没有修改密码，则不提交密码字段
      if (!submitData.password) {
        delete submitData.password
      }

      // 确保所有必填字段都有值
      if (!submitData.rolename) {
        ElMessage.error('请输入真实姓名')
        submitLoading.value = false
        return
      }

      const formData = new FormData()
      Object.keys(submitData).forEach(key => {
        formData.append(key, submitData[key])
      })

      axios({
        url: `/api/member/member/updateMember/${editForm.id}`,
        method: 'put',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then((res) => {
        if (res.data.code === 200) {
          ElMessage.success('修改成功')
          editDialogVisible.value = false
          getMemberList()
        } else {
          ElMessage.error(res.data.msg || '修改失败')
        }
      }).catch((error) => {
        console.error('修改错误:', error)
        ElMessage.error('修改失败')
      }).finally(() => {
        submitLoading.value = false
      })
    }
  })
}

onMounted(() => {
  getMemberList()
})
</script>

<style lang="scss" scoped>
.member-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
